
<script setup lang="ts" name="Dice">
import API from '@/api';
import { userinfo } from "@/store";
import { cloneDeep } from 'lodash';
import router from "@/router";

const { t } = useI18n();
const piniaUserinfo: any = userinfo();
const global: any = getCurrentInstance()?.appContext.config.globalProperties;
const route = useRoute();
const images = reactive({
    inputMoney: new URL("@/assets/images/ColorfulLottery/inputMoney.png", import.meta.url).href,
    inputMoneyActive: new URL("@/assets/images/ColorfulLottery/inputMoneyActive.png", import.meta.url).href,
});
const typeDigits = [
    { 
        bg: 'linear-gradient(97deg, #8F8FFE 1.52%, #6262FF 97.98%)',
        name: computed(() => t('bet.bet1')),
        money: '',
        id: 1,
    },
    {
        bg: 'linear-gradient(97deg, #FC6B6C 1.58%, #FB2973 110.2%)',
        name: computed(() => t('bet.bet2')),
        money: '',
        id: 2,
    },
    {
        bg: 'linear-gradient(97deg, #6AAFFF 1.52%, #3F70FC 97.98%)',
        name: computed(() => t('bet.bet3')),
        money: '',
        id: 3,
    },
    {
        bg: 'linear-gradient(107deg, #FFD56A 0%, #FF8159 81.21%)',
        name: computed(() => t('bet.bet4')),
        money: '',
        id: 4,
    }
]
const numDigits = [
    {
        bg: 'linear-gradient(97deg, #8F8FFE 1.52%, #6262FF 97.98%)',
        name: '0',
        money: '',
        id: 1,
        diceImg: new URL("@/assets/images/Dice/dice1.png", import.meta.url).href,
    },
    {
        bg: 'linear-gradient(97deg, #FC6B6C 1.58%, #FB2973 110.2%)',
        name: '1',
        money: '',
        id: 2,
        diceImg: new URL("@/assets/images/Dice/dice2.png", import.meta.url).href,
    },
    {
        bg: 'linear-gradient(97deg, #6AAFFF 1.52%, #3F70FC 97.98%)',
        name: '2',
        money: '',
        id: 3,
        diceImg: new URL("@/assets/images/Dice/dice3.png", import.meta.url).href,
    },
    {
        bg: 'linear-gradient(107deg, #FFD56A 0%, #FF8159 81.21%)',
        name: '3',
        money: '',
        id: 4,
        diceImg: new URL("@/assets/images/Dice/dice4.png", import.meta.url).href,
    },
    {
        bg: 'linear-gradient(97deg, #EA6AFF 1.52%, #A93FFC 97.98%)',
        name: '4',
        money: '',
        id: 5,
        diceImg: new URL("@/assets/images/Dice/dice5.png", import.meta.url).href,
    },
    {
        bg: 'linear-gradient(97deg, #8F8FFE 1.52%, #6262FF 97.98%)',
        name: '5',
        money: '',
        id: 6,
        diceImg: new URL("@/assets/images/Dice/dice6.png", import.meta.url).href,
    },
]
const entertainmentDes = computed(() => {
   return {
    title1: t('rule.title56'),
    title1Content:t('rule.test18'),
    title2: t('rule.title57'),
    title2Content:t('rule.test19'),
    }
}) 
    
const data: any = reactive({
    isShowPayFinished:false,
    tabList: [{
        text:computed(() => t('bet.type1'))
    }],
    tabIndex: 0,
    moneyList: ['50', '100', '1k', '5k', '10k'],
    moneyIndex: 0,
    isShowInput: false,
    money: '',
    hundredsMoney: 0,
    entertainmentList: [
        {
            titleName: computed(() => t('bet.position9')),
            id: 1,
            numberData:cloneDeep(typeDigits),
        },
        {
            titleName: computed(() => t('bet.position20')),
            id: 2,
            numberData: cloneDeep(numDigits),
        },
        {
            titleName: computed(() => t('bet.position21')),
            id: 3,
            numberData:cloneDeep(numDigits),
        },
        {
            titleName: computed(() => t('bet.position22')),
            id: 4,
            numberData:cloneDeep(numDigits),
        },
    ],
    showBet: false,
    showInstruction: false,
    nowMoney: '50',
    tempResultList: [],
    paramsResult: [],
    totalMoney: '',
    timer: null,
    routeParams: '',
    configList: []
})
const {
    tabList, tabIndex, moneyList, moneyIndex, isShowInput, nowMoney, routeParams,
    money,
    entertainmentList, showBet,isShowPayFinished, outOrInList, showInstruction, tempResultList, paramsResult, totalMoney,
} = toRefs(data);
let timer: any;

const headerTitle: any = computed(() => {
  return route?.query?.title || '摇骰子'
});

const startCountdown = () => {
    timer = setInterval(() => {
        if (routeParams.value.timeInfo > 0) {
            routeParams.value.timeInfo--;
        } else {
            clearInterval(timer);
            // 倒计时结束后的操作
        }
    }, 1000); // 每秒执行一次
};
const displayTime = computed(() => {
    const hours = Math.floor(routeParams.value.timeInfo / 3600);
    const minutes = Math.floor((routeParams.value.timeInfo% 3600) / 60);
    const seconds = Math.floor(routeParams.value.timeInfo % 60);
    return {
        hours: String(hours).padStart(2, '0'),
        min: String(minutes).padStart(2, '0'),
        seconds: String(seconds).padStart(2, '0')
    }
});
onMounted(() => {
});
onBeforeUnmount(() => {
    clearInterval(timer); // 组件销毁前清除计时器
});

const handleTab = (index: number) => {
    tabIndex.value = index
}

const setConfigData = (list: any) => {
    list.forEach((item: any) => {
        const str = item.type.split("_");
        let firstNum = str[0]
        if (firstNum == 1) {
            handleConfigData(entertainmentList.value, item);
        }
    })
}

const handleConfigData = (list: any, item: any) => {
    const str = item.type.split("_");
    let secondNum = str[1]
    let thirdNum = str[2]
    list.forEach((el: any) => {
        el.numberData.forEach((it: any) => {
            if (el.id == secondNum) {
                if (it.id == thirdNum) {
                    it.type = item.type,
                    it.odd = item.oddsRatio.toFixed(3),
                    it.singleMaxMoney = item.singleMaxMoney,
                    it.singleMinMoney = item.singleMinMoney
                }
            }
        })
    })
}
const handleMoney = (item: any, index: number) => {
    moneyIndex.value = index
    isShowInput.value = false
    nowMoney.value = item
}
const setCurrentMoney = (e: any) => {
    nowMoney.value = e.target.value
}
const handleInput = () => {
    isShowInput.value = true
    moneyIndex.value = -1
}
const cancelPop = () => {
    showBet.value = false
}
const getDefaultValue = () => {
    return nowMoney.value
}
const nowDes: any = computed(() => {
    switch (tabIndex.value) {
        case 0:
            return entertainmentDes.value
    }
})
const setDefaultMoney = (it: any) => {
    switch (nowMoney.value) {
        case '50':
            it.money = 50;
            break;
        case '100':
            it.money = 100;
            break;
        case '500':
            it.money = 500;
            break;
        case '1k':
            it.money = 1000;
            break;
        case '5k':
            it.money = 5000;
            break;
        case '10k':
            it.money = 10000;
            break;
        default:
            it.money = nowMoney.value
    }
}
const betInterval = (e: any, data: any) => {
    let money = e.target.value
    if (money > data.singleMaxMoney) {
        data.money = data.singleMaxMoney
    } else if (money < data.singleMinMoney) {
        if (data.singleMinMoney == 0) {
            data.money = ''
        } else {
            data.money = data.singleMinMoney
        }
    } else {
        data.money = money
    }
}
const handleBet = () => {
    if ( routeParams.value.timeInfo <= routeParams.value.timeRange) {
        global.message( t('bet.warning1'),{type: 'danger'} )
        return false
    }
    paramsResult.value = [] //组装数据结果
    tempResultList.value = [] //投注确认详情
    let newArray: any = []
    switch (tabIndex.value) {
        case 0:
            newArray = entertainmentList.value;
            break;
        default:
            newArray = []
    }
    totalMoney.value = 0
    newArray.forEach((item: any, groupIndex: number) => {
        let hasMoenyList = item.numberData.filter((el: any) => el.money)
        if (hasMoenyList.length > 0) {
            console.log(hasMoenyList, 'hasMoenyList');
            hasMoenyList.forEach((it: any, index: number) => {
                let firstData = tabIndex.value + 1
                let secondData = item.id
                let thirdData = it.id
                let dataInfo = `${firstData}-${secondData}-${thirdData}`
                let dataMoney = it.money
                paramsResult.value.push(`${dataInfo}:${dataMoney}`)
                let zeroName = tabList.value[tabIndex.value].text
                let firstName = newArray[groupIndex].titleName || '';
                let secondName = it.name || ''
                let oddNum = it.odd
                tempResultList.value.push({
                    name: `${zeroName} ${firstName} ${secondName}`,
                    money: dataMoney,
                    odds: oddNum || 0,
                    type: it.type
                })
                totalMoney.value = tempResultList.value.reduce((accumulator: any, currentValuea: any) => {
                    return +accumulator + +currentValuea.money;
                }, 0);
            })
        } 
    });

    console.log(paramsResult.value, 'paramsResult.value');
    console.log(tempResultList.value, 'tempResultList--------');
    if(tempResultList.value.length <= 0) {
        global.message(t('bet.warning2'),{type: 'danger'} )
        return
    }
    showBet.value = true;
}
const resetMoney = () => {
    entertainmentList.value.forEach((item: any) => {
        clearInput(item.numberData)
    })
}
const clearInput = (list: any) => {
    list.forEach((it: any) => {
        it.money = ''
    })
}
const submitBet = async () => {
    let betContent = tempResultList.value.map((item: any) => {
        return {
            money: item.money,
            content: item.type,
            name:item.name
        }
    })
    let params = {
        privateId: route?.query?.id,
        allMoney: totalMoney.value,
        betContent: betContent,
        code: tabIndex.value+1,
        period: routeParams.value.period,
        bigCode: route?.query?.bigCode,
        typeConfigCode: route?.query?.typeConfigCode
    }
    try {
        let res = await API.privateOrderBetApi(params);
        if (res?.code === 200) {
            piniaUserinfo.queryUserMoney();
            refreshPage()
            isShowPayFinished.value = true;
        }
    } catch (error) {
    }
}
// 查看历史
const handleGoHistory = () => {
  router.push(`/me/account?type=${route?.query?.typeConfigCode}`);
};
const refreshPage = async() => {
    try {
    let res = await API.lotteryPrivateAPI({planId:route?.query?.planId, typeConfigCode: route?.query?.typeConfigCode});
    if(res?.code === 200) {
        let data = res.data.periods[0]
        let timeInfo = Math.floor((data?.endTime - res.data.time)/1000) + 1
        let timeRange = Math.floor((data?.endTime - data?.stopBetTime)/1000)
        routeParams.value = {
            ...data,timeInfo,timeRange
        }
        clearInterval(timer);
        startCountdown()
        setConfigData(res.data.typeList)
    }
  } catch (error) {
  }
}
const closeDialog = () => {
    showBet.value = false
}
watch(
  [() => route?.query?.planId, () => route?.query?.typeConfigCode],
  ([val1, val2]) => {
    if (val1 && val2) {
      refreshPage()
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => routeParams.value.timeInfo,
  (val) => {
    if (val == 0) {
      refreshPage()
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
    <DetailHeader :title="headerTitle" :isNeedBackIcon="true" />
    <div class="colorfulLotteryPage">
        <van-tabs class="headerTabs" v-model:active="tabIndex" swipe-threshold="1" shrink>
            <van-tab v-for="(el, index) in tabList" :title="el?.text">
            </van-tab>
        </van-tabs>
        <div class="moneyNum">
            <div class="moneyItem" v-for="(el, index) in moneyList" :key="index"
                :class="{ 'moneyActive': moneyIndex === index }" @click="handleMoney(el, index)">
                {{ el }}
            </div>
            <div class="inputMoney">
                <img v-if="!isShowInput" :src="images.inputMoney" alt="" @click="handleInput">
                <img v-else :src="images.inputMoneyActive" alt="">
                <input v-model="money" @input="setCurrentMoney" v-if="isShowInput" type="number" :placeholder="t('bet.test57')">
            </div>
        </div>
        <div class="bottomInfo">
            <div class="countdown">
                <div class="topTime">
                    <div class="leftNum">{{ t('bet.test38') }}{{ routeParams.period }}{{ t('bet.test39') }}</div>
                    <div class="dateTime">{{ t('bet.test40') }}</div>
                    <div class="timeData">
                        <div class="timeInfo">{{ displayTime.hours }}</div> :
                        <div class="timeInfo">{{ displayTime.min }}</div> :
                        <div class="timeInfo">{{ displayTime.seconds }}</div>
                    </div>
                </div>
                <div class="line"></div>
                <div class="topTime">
                    <div class="leftNum" v-if="routeParams.lastPeriod != null">{{ t('bet.test38') }}{{ routeParams.lastPeriod || '' }}{{ t('bet.test39') }}</div>
                    <div class="dateTime">{{ t('bet.test41') }}</div>
                    <div class="resultData">
                        <div class="numItem" v-if="routeParams.winningNumber != null" v-for="(item) in routeParams.winningNumber">{{ item }}</div>
                    </div>
                </div>
            </div>
            <div class="playContainer">
                <div class="playTypeItem" v-if="tabIndex === 0" v-for="(item, parentIndex) in entertainmentList"
                    :key="parentIndex">
                    <div class="topTitle">{{ item.titleName }}</div>
                    <template v-if="item.id < 2">
                        <div class="bottomData">
                            <div class="firstRow">
                                <div class="name">{{ t('bet.test42') }}</div>
                                <div class="type">
                                    <div class="num1" :style="{ background: num.bg }" v-for="(num, index) in item.numberData"
                                        :key="index">{{ num.name }}</div>
                                </div>
                            </div>
                            <div class="secondRow">
                                <div class="name">{{ t('bet.test43') }}</div>
                                <div class="Odds">
                                    <div v-for="(el, index) in item.numberData" :key="el.id">
                                        {{ el.odd }}
                                    </div>
                                </div>
                            </div>
                            <div class="thirdRow">
                                <div class="name">{{ t('bet.test44') }}</div>
                                <div class="moneyInfo">
                                    <div class="inputMoney" :class="{'showMinWidth':it.showMinWidth}" v-for="(it, index) in item.numberData" :key="it.id">
                                        <input type="number" v-model="it.money" @focus="setDefaultMoney(it)" 
                                            @blur="(e) => betInterval(e, it)">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                    <div class="content" v-else>
                        <div class="left-bar">
                            <div>{{ t('bet.test42') }}</div>
                            <div>{{ t('bet.test43') }}</div>
                            <div>{{ t('bet.test44') }}</div>
                            <div>{{ t('bet.test42') }}</div>
                            <div>{{ t('bet.test43') }}</div>
                            <div>{{ t('bet.test44') }}</div>
                        </div>
                        <div class="list">
                            <div class="bottomData" v-for="el in item.numberData">
                                <div class="diceImg"><img :src="el.diceImg" alt=""></div>
                                <div class="rate">{{ el.odd }}</div>
                                <input class="input diceInput" v-model="el.money" @focus="setDefaultMoney(el)" @blur="(e) => betInterval(e, el)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> 
        <div class="betAction">
            <div @click="showInstruction = true" class="winningRemark">
                <Iconfont name="icon-icon_shuoming" color="#FF6F1E" size="20" class="remarkIcon" /><span>{{ t('bet.test45') }}</span>
            </div>
            <van-button round class="reset" type="primary" @click="resetMoney">{{ t('bet.btn4') }}</van-button>
            <van-button @click="handleBet" round class="bet" type="primary">{{ t('bet.btn5') }}</van-button>
        </div>
        <van-popup v-model:show="showBet" round position="bottom" class="confirmBetPop">
            <div class="popTitle">
                <div>{{ t('bet.test46') }}</div>
                <Iconfont @click="cancelPop" class="closeIcon" name="icon-icon_close" color="#FF2D55" size="20" />
            </div>
            <div class="centerContent">
                <div class="betDetail">
                    <div class="detailRow">
                        <div>{{ t('bet.test47') }}<span>{{ routeParams.planName }}</span></div>
                        <div>{{ t('bet.test48') }}</div>
                        <div class="rowWrap">
                            <div class="rowData" v-for="(item, index) in tempResultList" :key="index">
                                <span>{{ item.name }} </span>
                                <span class="money">₹{{ item.money }}</span>
                            </div>
                        </div>
                        <div>{{ t('bet.test49') }}：<span><span class="period">{{ routeParams.period }}</span> {{ t('bet.test39') }}</span></div>
                        <div>{{ t('bet.test55') }}：<span class="totalMoney">₹{{ Number(totalMoney).toFixed(2) }}</span></div>
                    </div>
                </div>
                <div class="operateBtn">
                    <van-button class="cancel" round type="primary" @click="showBet=false">{{ t('bet.btn6') }}</van-button> 
                    <van-button class="confirm" round @click="submitBet" type="primary"
                        :disabled="!tempResultList.length">{{ t('bet.btn7') }}</van-button>
                </div>
            </div>
        </van-popup>
        <van-popup v-model:show="showInstruction" round position="bottom" class="confirmBetPop">
            <div class="popTitle">
                <div>{{ t('bet.test45') }}</div>
                <Iconfont @click="showInstruction = false" class="closeIcon" name="icon-icon_close" color="#FF2D55"
                    size="20" />
            </div>
            <div class="remarkContent">
                <div class="titleName">{{ nowDes?.title1 }}</div>
                <div class="contentDetail">{{ nowDes?.title1Content }}</div>
                <div class="titleName">{{ nowDes?.title2 }}</div>
                <div class="contentDetail">{{ nowDes?.title2Content }}</div>
                <div class="titleName">{{ nowDes?.title3 }}</div>
                <div class="contentDetail">{{ nowDes?.title3Content }}</div>
            </div>
        </van-popup>
        <van-dialog
            class="payDialog"
            v-model:show="isShowPayFinished"
            :title="t('bet.test56')"
            show-cancel-button
            @cancel="closeDialog"
            :cancel-button-text="t('bet.btn2')"
            cancel-button-color="#9CA2A9"
            :confirm-button-text="t('bet.btn3')"
            confirm-button-color="#3497FB"
            @confirm="handleGoHistory"
            >
            <img src="@/assets/images/Bet/success.svg" alt=""/>
        </van-dialog>
    </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
<style lang="scss">
.payDialog {
  text-align: center;
  .van-dialog__header {
    color: #ff2d55;
  }
  .van-dialog__content {
    img {
      margin: 15rem auto;
      width: 50rem;
      height: 50rem;
    }
  }
}
</style>
